package itsm.isperp.framework.security.authentication;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.UserStatus;
import itsm.isperp.framework.security.license.LicenseUtils;
import itsm.isperp.module.entity.app.AppLoginLog;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.service.app.AppLoginLogService;
import itsm.isperp.module.service.app.AppUserService;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2014-2-25
 * @since 1.0
 * 
 */
public class IsperpAuthenticationSuccessHandler implements
		AuthenticationSuccessHandler {

	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException {
		handle(request, response, authentication);
		clearAuthenticationAttributes(request);
	}

	protected void handle(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException {
		String targetUrl = null;

		if (!LicenseUtils.validata()) {
			targetUrl = "/license?error=true";
			redirectStrategy.sendRedirect(request, response, targetUrl);
			return;
		}

		if (response.isCommitted()) {
			return;
		}
		targetUrl = request.getParameter("targetUrl");

		// 记录到日志表中
		AppLoginLogService appLoginLogService = ContextHolder
				.getSpringBean("appLoginLogService");

		String ip = null;
		if (request.getHeader("x-forwarded-for") == null) {
			ip = request.getRemoteAddr();
		} else {
			ip = request.getHeader("x-forwarded-for");
		}
		AppUser user = (AppUser) authentication.getPrincipal();

		if ("locked".equals(user.getStatus())) {
			AppUserService appUserService = ContextHolder
					.getSpringBean(AppUserService.class);
			appUserService.updateUserStatus(UserStatus.used, user.getName());
		}
		AppLoginLog entity = new AppLoginLog();
		entity.setUsername(authentication.getName());
		entity.setCreatedDate(new Timestamp(new Date().getTime()));
		entity.setInfo("登录成功");
		entity.setSuccess(true);
		entity.setIp(ip);
		appLoginLogService.saveOrUpdate(entity);

		Collection<? extends GrantedAuthority> c = user.getAuthorities();

		if (c.size() == 0) {
			targetUrl = "/customer/help/user";
		}
		redirectStrategy.sendRedirect(request, response, targetUrl);
	}

	protected void clearAuthenticationAttributes(HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		if (session == null) {
			return;
		}
		session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
	}

	public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
		this.redirectStrategy = redirectStrategy;
	}

	protected RedirectStrategy getRedirectStrategy() {
		return redirectStrategy;
	}
}
